//#include "stdafx.h"
#include "mswin/seq_name_factory.h"
#include "mswin/file_dir.h"
#include <sstream>

namespace mswin {

seq_name_factory::seq_name_factory(string const & pattern)
{
	if (!pattern.empty())
		init(pattern);
}

void seq_name_factory::init(string const & pattern)
{
	current_ = 0;
	string::size_type end = pattern.find_last_of('#');
	if (end == string::npos) {
		string drive, dir, title;
		mswin::splitpath(pattern, &drive, &dir, &title, &suffix_);
		prefix_ = drive + dir + title;
		digits_ = 3;
		return;
	}
	string::size_type begin = pattern.find_last_not_of('#', end);

	digits_ = 0;
	++end;
	if (end < pattern.size() && pattern[end] == ']') {
		++end;
		--digits_;
	}

	if (begin == string::npos)
		begin = 0;
	else {
		if (pattern[begin] != '[')
			++begin;
		else
			--digits_;
	}

	prefix_ = pattern.substr(0, begin);
	suffix_ = pattern.substr(end);
	digits_ += end - begin;
}

string seq_name_factory::get_next()
{
	std::ostringstream s;
	s << prefix_;
	s.width(digits_);
	s.fill('0');
	s << current_++ << suffix_;
	return s.str();
}

string seq_name_factory::propose_pattern(string const & name)
{
	string drive, dir, title, ext;
	mswin::splitpath(name, &drive, &dir, &title, &ext);
	return drive + dir + title + "_[###]" + ext;
}

} //namespace irender
